<!-- 组织管理 -->
<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import type { IDbAction, IDbSearchConfig, IDbSelect, IDbTable } from '@/types/global'
import useNotic from '@/hooks/useNotic'
import * as orgApi from '@/api/org'
import { ENUM_BTN_AUTH_SYS } from '@/config/btn'
import OrgInfo from './comps/OrgInfo.vue'
import OrgBind from './comps/OrgBind.vue'

// 搜索栏配置
const orgTypeList = ref<IDbSelect[]>([])
const searchConfig = computed<IDbSearchConfig[]>(() => {
  return [
    { label: '组织类型', prop: 'orgType', type: 'select', options: { clearable: false }, list: orgTypeList.value }
  ]
})
// 表格数据
const tableData = reactive<IDbTable>({
  columns: [
    { label: '组织名称', prop: 'orgName', align: 'left', minWidth: '200px' },
    { label: '操作', prop: 'handle', fixed: 'right', type: 'slot', width: '150px' }
  ],
  data: [],
  search: {
    orgType: ''
  }
})

// 弹窗数据
const orgRef = ref<InstanceType<typeof OrgInfo>>()
const bindRef = ref<InstanceType<typeof OrgBind>>()
const dialogData = reactive({
  title: '', // 详情弹窗标题
  disabled: false, // 是否禁用
  titleBind: '' // 绑定弹窗标题
})

initData()
/**
 * 获取表格数据
 */
function getDataList() {
  orgApi.getChildrenByOrgId(tableData.search).then((res) => {
    if (res.success) {
      tableData.data = []
      const rowList = res.data.rows || []
      rowList.forEach((item: any) => {
        if (item.parentId == 1) {
          tableData.data.push(item)
        } else {
          for (let row of rowList) {
            if (item.parentId == row.id) {
              if (!row.children) {
                row.children = []
              }
              row.children.push(item)
              break
            }
          }
        }
      })
    }
  })
}
/**
 * 点击添加
 */
function addClick() {
  dialogData.title = '添加组织'
  dialogData.disabled = false
  orgRef.value?.init({ parentName: '根组织', parentId: 1, orgType: '' })
}
/**
 * 点击添加-子节点
 */
function addChildClick(row: any) {
  dialogData.title = '添加组织'
  dialogData.disabled = false
  orgRef.value?.init({ parentName: row.orgName, parentId: row.id, orgType: row.typeCode }, true)
}
/**
 * 点击详情/编辑
 */
function infoClick(row: any, disabled: boolean) {
  dialogData.title = disabled ? '组织详情' : '编辑组织'
  dialogData.disabled = disabled
  const params = { parentName: row.parentName, parentId: row.parentId, orgType: row.typeCode }
  if (params.parentId == 1) {
    params.parentName = '根组织'
  }
  orgRef.value?.init({ ...row, ...params })
}
/**
 * 点击绑定
 */
function bindClick(row: any) {
  dialogData.titleBind = `${row.orgName}-绑定组织`
  bindRef.value?.init(row.id)
}
/**
 * 点击删除
 */
function delClick(scoped: any) {
  useNotic().confirm(`您确定要删除<${scoped.row.orgName}>吗？`, (flag) => {
    if (flag) {
      orgApi.delOrg(scoped.row.id).then((res) => {
        if (res.success) {
          useNotic().success('删除成功')
          getDataList()
        }
      })
    }
  })
}
/**
 * 设置表格按钮
 */
function setBtnList(scoped: any) {
  const list: IDbAction[] = [
    {
      label: '添加',
      type: 'primary',
      auth: ENUM_BTN_AUTH_SYS['组织管理:增'],
      onClick: () => addChildClick(scoped.row)
    },
    {
      label: '详情',
      type: 'primary',
      auth: ENUM_BTN_AUTH_SYS['组织管理:查'],
      onClick: () => infoClick(scoped.row, true)
    },
    {
      label: '编辑',
      type: 'primary',
      auth: ENUM_BTN_AUTH_SYS['组织管理:改'],
      onClick: () => infoClick(scoped.row, false)
    },
    { label: '绑定', type: 'primary', auth: ENUM_BTN_AUTH_SYS['组织管理:绑定'], onClick: () => bindClick(scoped.row) },
    { label: '删除', type: 'danger', auth: ENUM_BTN_AUTH_SYS['组织管理:删'], onClick: () => delClick(scoped) }
  ]
  return list
}
/**
 * 初始化数据
 */
function initData() {
  orgApi.getOrgTypeByPage({ pageNum: 1, pageSize: 99 }).then((res) => {
    if (res.success) {
      orgTypeList.value = res.data.rows.map((item: any) => {
        return { label: item.typeName, value: item.typeCode }
      })
      // 默认选中第一个组织类型
      tableData.search!.orgType = orgTypeList.value[0].value ?? ''
      getDataList()
    }
  })
}
</script>

<template>
  <dui-page :search-config="searchConfig" :search-data="tableData.search" @search="getDataList">
    <template #btn>
      <db-auth-btn :auth="ENUM_BTN_AUTH_SYS['组织管理:增']" type="primary" iconType="add" @click="addClick">
        添加组织
      </db-auth-btn>
    </template>
    <template #default>
      <dui-table
        :data="tableData.data"
        :columns="tableData.columns"
        :total="tableData.total"
        :search="tableData.search"
        :isPagination="false"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <template #handleSlot="scoped">
          <dui-action :list="setBtnList(scoped)" />
        </template>
      </dui-table>
      <!-- 详情弹窗 -->
      <OrgInfo ref="orgRef" :types="orgTypeList" v-bind="dialogData" @refresh="getDataList" />
      <!-- 绑定弹窗 -->
      <OrgBind ref="bindRef" :title="dialogData.titleBind" />
    </template>
  </dui-page>
</template>
